<?php
namespace Credentials;
// require 'vendor/autoload.php'; // 引入Composer自动加载文件

// Use environment variable for include path if available
if (getenv('PHP_INCLUDE_PATH')) {
    set_include_path(get_include_path() . PATH_SEPARATOR . getenv('PHP_INCLUDE_PATH'));
}
require_once 'pkg/client/client.php';
require_once 'pkg/openapi/openapi.php';
use GuzzleHttp\Client; // 使用Guzzle进行HTTP请求
use Ramsey\Uuid\Uuid; // 生成唯一标识符
use DateTime; // 处理时间
use DateTimeZone; // 处理时区

class credentials {
    private $AK;
    private $SK;

    public function __construct($AK, $SK) {
        $this->AK = $AK;
        $this->SK = $SK;
    }

    public function doCTAPIRequest($request): mixed {
        $reqURL = $request->url;
        $method = $request->method;
        $headers = $request->headers;
        $data = $request->data ?? [];
        $query = $request->query ?? [];

        $queryStr = $this->getCTAPISortedQueryString($query);
        if ($queryStr !== '') {
            $reqURL .= '?' . $queryStr;
        }

        $reqBody = '';
        if (!empty($data)) {
            if ($headers['Content-Type'] === 'application/json') {
                $reqBody = json_encode($data);
                $headers['Content-Type'] = 'application/json; charset=utf-8';
            } else {
                $reqBody = http_build_query($data);
                $headers['Content-Type'] = 'application/x-www-form-urlencoded';
            }
        }

        unset($headers['regionId']);
        $uuid = $this->generateUUID();
        $timezone = new DateTimeZone('Asia/Shanghai');
        $eopDate = (new DateTime('now', $timezone))->format('Ymd\THis') . 'Z';
        $authorization = $this->getCTAPIAuthorization($queryStr, $reqBody, $uuid, $this->AK, $this->SK, $eopDate);

        $config = [
            'headers' => array_merge($headers, [
                'User-Agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:109.0) Gecko/20100101 Firefox/110.0',
                'Ctyun-Eop-Request-Id' => $uuid,
                'Eop-Date' => $eopDate,
                'Eop-Authorization' => $authorization,
                'Content-Length' => strlen($reqBody),
            ]),
            'body' => $reqBody,
            'verify' => false, // 禁用SSL证书验证，仅用于测试环境
        ];

        $client = new Client();
        try {
            $response = $client->request($method, $reqURL, $config);
            $data = $response->getBody()->getContents();
            return $data;
        } catch (\Exception $e) {
            throw $e;
        }
    }

    private function generateUUID(): mixed {
        return Uuid::uuid4()->toString();
    }

    private function getCTAPISortedQueryString($query): string {
        $queryArray = [];
        foreach ($query as $key => $value) {
            $queryArray[] = "$key=$value";
        }
        // 构建URL查询字符串格式
        return implode('&', $queryArray);
    }

    private function getCTAPIAuthorization($query, $body, $uuid, $ak, $sk, $timestamp) {
        $hashedRequestBody = hash('sha256', $body); // 已对hash结果进行hex digest处理
        $signature = "ctyun-eop-request-id:$uuid\neop-date:$timestamp\n\n$query\n$hashedRequestBody";
        $ktime = $this->signatureMethod($sk, $timestamp, 'sha256');
        $kak = $this->signatureMethod($ktime, $ak, 'sha256');
        $kdate = $this->signatureMethod($kak, substr($timestamp, 0, 8), 'sha256');
        $signaSha256 = $this->signatureMethod($kdate, $signature, 'sha256');
        $base64Signa = base64_encode($signaSha256);
        $signHeader = "$ak Headers=ctyun-eop-request-id;eop-date Signature=$base64Signa";
        return $signHeader;
    }

    private function signatureMethod($key, $message, $algorithm): string {
        // 返回未base64编码的二进制哈希值
        return hash_hmac($algorithm, $message, $key, true);
    }
}

?>